package com;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Main {
	public static int PORT = 12345;
	public static String chromeUrl = null;

	public static String getUrl() {
		String app = WindowsApi.getForegroundWindow();
		if (app.contains("Google Chrome") || app.contains("Firefox")) {
			return chromeUrl;
		}
		return "exe://" + app;
	}

	public static String txmy;

	public static void main(String[] args) throws Exception {
		// /w 7980 /b /i 127.0.0.1 7980 code
		//args = new String[] { "test123", "/w", "7888" };

		if (args.length < 2) {
			System.out.println("参数错误");
			return;
		}
		MsgHandler.init();
		txmy = args[0];
		for (int i = 1; i < args.length; i++) {
			switch (args[i]) {
			case "/w":
				PORT = Integer.parseInt(args[++i]);
				new Thread(new Runnable() {

					@Override
					public void run() {
						Main a = new Main();
						a.initSocket();
					}
				}).start();
				break;
			case "/b":
				new Thread(new Runnable() {

					@Override
					public void run() {
						Bluetooth bt = new Bluetooth();
						try {
							bt.init();
						} catch (Exception e) {
							System.out.println("蓝牙错误：" + e.getMessage());
							e.printStackTrace();
						}
					}
				}).start();
				break;
			case "/i":
				final String server = args[++i];
				final int serverport = Integer.parseInt(args[++i]);
				final String code = args[++i];
				new Thread(new Runnable() {

					@Override
					public void run() {
						while (true) {
							WWWSocket ww = new WWWSocket(server, serverport, code);
							try {
								ww.start();
							} catch (IOException | InterruptedException e) {
								e.printStackTrace();
							}
							while (!ww.IsClose()) {
								try {
									Thread.sleep(1000);
								} catch (InterruptedException e) {
									e.printStackTrace();
								}
							}
							try {
								Thread.sleep(1000);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						}
					}
				}).start();
				break;
			}
		}

		SHttp a = new SHttp();
		a.initSocket();
	}

	void initSocket() {
		try {
			ServerSocket serverSocket = new ServerSocket(PORT);
			while (true) {
				// 一旦有堵塞, 则表示服务器与客户端获得了连接
				Socket client = serverSocket.accept();
				// 处理这次连接
				new HttpHandlerThread2(client);
			}
		} catch (Exception e) {
			System.out.println("服务器异常: " + e.getMessage());
		}
	}
}
